package com.lsh.oms.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.oms.core.model.order.AtpHoldDetail;
import com.lsh.oms.core.model.order.OrderShippingDetail;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.utils.model.Good;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author peter
 */
public class GoodsServiceUtils extends BaseGoodUtils {

    private static Logger log = LoggerFactory.getLogger(GoodsServiceUtils.class);

    public static Map<String, Good> getCode2GoodMaps(AtpHoldDetail atpHoldDetail, Map<Long, Long> orderDetailMap, String shopServiceUrl, Long venderId, String logSign) {

        List<Long> skuIds = new ArrayList<>();
        for (Long skuCode : atpHoldDetail.getSkuCodes()) {
            Long goodsCode = orderDetailMap.get(skuCode);
            if (null == goodsCode) {
                continue;
            }
            skuIds.add(goodsCode);
        }

        if (skuIds.isEmpty()) {
            return Collections.EMPTY_MAP;
        }
        List<BasicNameValuePair> paramPairs = new ArrayList<>(5);
        paramPairs.add(new BasicNameValuePair("sku_id", skuIds.toString()));
        paramPairs.add(new BasicNameValuePair("venderId", venderId + ""));
//        paramPairs.add(new BasicNameValuePair(GoodsConstants.SUPPLY_ORG_NAME, String.valueOf(atpHoldDetail.getSupplierOrg())));
//        paramPairs.add(new BasicNameValuePair(GoodsConstants.SUPPLY_DC_NAME, atpHoldDetail.getDc()));

        HttpEntity entity = new UrlEncodedFormEntity(paramPairs, Consts.UTF_8);
        shopServiceUrl = shopServiceUrl + SAAS_GETINFOS;
        log.info(logSign + "【请求商品服务url:{}】 【params is {}】", shopServiceUrl, JSON.toJSONString(paramPairs));
        JSONObject goodsInfoResp = doReqSaas(shopServiceUrl, entity, buildHeaders(venderId), logSign);

        if (!goodsInfoResp.getString("ret").equals("0")) {
            log.info(logSign + "【商品服务返回结果失败】");
            return Collections.emptyMap();
        }
        JSONArray contentArray = goodsInfoResp.getJSONArray("content");
        if (contentArray == null || contentArray.isEmpty()) {
            log.error("商品信息不存在！shopServiceUrl=" + shopServiceUrl);
            return Collections.emptyMap();
        }

        Map<Long, JSONObject> contentMap = new HashMap<>();
        for (int i = 0; i < contentArray.size(); i++) {
            JSONObject content = contentArray.getJSONObject(i);

            JSONObject skuInfo = content.getJSONObject("sku_info");
            if (skuInfo == null) {
                continue;
            }
            Long goodscode = skuInfo.getLong("sku_id");

            contentMap.put(goodscode, content);
        }
        Map<String, Good> item2GoodsMap = new HashMap<>();

        // 2019-12-18
        for (Long skuCode : atpHoldDetail.getSkuCodes()) {
            Long goodsCode = orderDetailMap.get(skuCode);
            JSONObject content = contentMap.get(goodsCode);
            if (content == null) {
                log.error("商品信息不存在！content goodsCode=" + goodsCode);
                continue;
            }
            JSONObject goodsInfo = content.getJSONObject("goods_info");
            JSONObject itemInfo = content.getJSONObject("item_info");
            JSONObject skuInfo = content.getJSONObject("sku_info");

            if (goodsInfo == null) {
                log.error("商品信息不存在 goodsInfo ！goodsCode=" + goodsCode);
                continue;
            }
            if (itemInfo == null) {
                log.error("商品信息不存在 itemInfo ！goodsCode=" + goodsCode);
                continue;
            }
            if (skuInfo == null) {
                log.error("商品信息不存在 skuInfo ！goodsCode=" + goodsCode);
                continue;
            }
            Good goods = new Good();
            goods.setGoodsCode(goodsCode);
            goods.setGoodsSaleUnit(skuInfo.getBigDecimal("sale_unit"));
            goods.setSkuCode(goodsInfo.getLong("item_id"));
            goods.setSupplySkuCode(goodsInfo.getString("goods_id"));
            goods.setSupplierOrg(atpHoldDetail.getSupplierOrg());
            item2GoodsMap.put(goodsInfo.getString("goods_id"), goods);
        }

        return item2GoodsMap;
    }

    public static Map<Long, Good> getItem2GoodsMaps(AtpHoldDetail atpHoldDetail, Map<Long, List<Long>> orderDetailMap, String shopServiceUrl, Long venderId, String logSign) {

        List<Long> skuIds = new ArrayList<>();
        for (Long skuCode : atpHoldDetail.getSkuCodes()) {
            List<Long> goodsCode = orderDetailMap.get(skuCode);
            if (null == goodsCode) {
                continue;
            }
            skuIds.addAll(goodsCode);
        }

        if (skuIds.isEmpty()) {
            return Collections.EMPTY_MAP;
        }
        List<BasicNameValuePair> paramPairs = new ArrayList<>(5);
        paramPairs.add(new BasicNameValuePair("sku_id", skuIds.toString()));
        paramPairs.add(new BasicNameValuePair("venderId", venderId + ""));
//        paramPairs.add(new BasicNameValuePair(GoodsConstants.SUPPLY_ORG_NAME, String.valueOf(atpHoldDetail.getSupplierOrg())));
//        paramPairs.add(new BasicNameValuePair(GoodsConstants.SUPPLY_DC_NAME, atpHoldDetail.getDc()));

        HttpEntity entity = new UrlEncodedFormEntity(paramPairs, Consts.UTF_8);
        shopServiceUrl = shopServiceUrl + SAAS_GETINFOS;
        log.info(logSign + "【请求商品服务url:{}】 【params is {}】", shopServiceUrl, JSON.toJSONString(paramPairs));
        JSONObject goodsInfoResp = doReqSaas(shopServiceUrl, entity, buildHeaders(venderId), logSign);

        if (!goodsInfoResp.getString("ret").equals("0")) {
            log.info(logSign + "【商品服务返回结果失败】");
            return Collections.emptyMap();
        }
        JSONArray contentArray = goodsInfoResp.getJSONArray("content");
        if (contentArray == null || contentArray.isEmpty()) {
            log.error("商品信息不存在！shopServiceUrl=" + shopServiceUrl);
            return Collections.emptyMap();
        }

        Map<Long, JSONObject> contentMap = new HashMap<>();
        for (int i = 0; i < contentArray.size(); i++) {
            JSONObject content = contentArray.getJSONObject(i);

            JSONObject skuInfo = content.getJSONObject("sku_info");
            if (skuInfo == null) {
                continue;
            }
            Long goodscode = skuInfo.getLong("sku_id");

            contentMap.put(goodscode, content);
        }
        Map<Long, Good> item2GoodsMap = new HashMap<>();

        // 2019-12-18
        for (Long skuCode : atpHoldDetail.getSkuCodes()) {
            List<Long> goodsCodes = orderDetailMap.get(skuCode);
//            Long goodsCode = goodsCodes.get(0);
            for (Long goodsCode : goodsCodes) {
                JSONObject content = contentMap.get(goodsCode);
                if (content == null) {
                    log.error("商品信息不存在！content goodsCode=" + goodsCode);
                    continue;
                }
                JSONObject goodsInfo = content.getJSONObject("goods_info");
                JSONObject itemInfo = content.getJSONObject("item_info");
                JSONObject skuInfo = content.getJSONObject("sku_info");

                if (goodsInfo == null) {
                    log.error("商品信息不存在 goodsInfo ！goodsCode=" + goodsCode);
                    continue;
                }

                if (itemInfo == null) {
                    log.error("商品信息不存在 itemInfo ！goodsCode=" + goodsCode);
                    continue;
                }
                if (skuInfo == null) {
                    log.error("商品信息不存在 skuInfo ！goodsCode=" + goodsCode);
                    continue;
                }
                Good goods = new Good();
                goods.setGoodsCode(goodsCode);
                goods.setGoodsSaleUnit(skuInfo.getBigDecimal("sale_unit"));
                goods.setSkuCode(goodsInfo.getLong("item_id"));
                goods.setSupplySkuCode(goodsInfo.getString("goods_id"));
                goods.setSupplierOrg(atpHoldDetail.getSupplierOrg());
                item2GoodsMap.put(goodsCode, goods);
            }
        }

        return item2GoodsMap;
    }

    /**
     * 常温品签收-销售码签收
     */
    public static JSONObject getReceiptServiceResp(List<Map<String, Object>> items, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> osds, String uri, String logSign, Long venderId) throws BusinessException {

        JSONArray skuList = new JSONArray(items.stream().map($ -> {
            JSONObject item = new JSONObject();
            item.put("sku_id", $.get("sku_id"));
            item.put("item_code", $.get("item_code"));
            item.put("qty", $.get("qty"));
            return item;
        }).collect(Collectors.toList()));

        JSONArray shippingInfoDetailList = new JSONArray(osds.size());
        for (OrderShippingDetail osd : osds) {
            JSONObject item = JSON.parseObject(osd.getExt());
            item.put("item_code", osd.getItemCode());
            item.put("sku_id", osd.getSkuId().toString());
            item.put("sku_name", osd.getSkuName());
            item.put("sale_unit", osd.getSaleUnit().toString());
            item.put("real_qty", osd.getRealQty());
            item.put("qty", osd.getQty());
            item.put("money", osd.getMoney().toString());
            item.put("price", osd.getPrice().toString());
            shippingInfoDetailList.add(item);
        }
        JSONObject shipExt = JSON.parseObject(osh.getExt());
        log.info(logSign + ",shipExt ext " + shipExt.toJSONString());
        JSONObject extHeadInfo = shipExt.getJSONObject("head_info");
        log.info(logSign + ",shipExt ext head_info " + extHeadInfo.toJSONString());
        JSONObject shippingInfoParams = new JSONObject();

        shippingInfoParams.put("head_info", extHeadInfo);
        shippingInfoParams.put("detail_list", shippingInfoDetailList);

        List<BasicNameValuePair> pairs = new ArrayList<>(3);
        pairs.add(new BasicNameValuePair("order_id", osh.getOrderId().toString()));
        pairs.add(new BasicNameValuePair("sku_list", skuList.toJSONString()));
        pairs.add(new BasicNameValuePair("shipping_info", shippingInfoParams.toJSONString()));
        HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
        log.info(logSign + ",签收请求计算服务参数shipping_info:" + shippingInfoParams.toJSONString());
        log.info(logSign + ",签收请求计算服务参数sku_list:" + skuList.toJSONString());
        String result = HttpUtils.post(uri, entity, false, BaseGoodUtils.buildHeaders(venderId)).getData();
        log.info(logSign + ",签收请求计算服务返回:" + result);

        return JSON.parseObject(result).getJSONObject("content");
    }

//    /**
//     *
//     * @param orderReceiptItem
//     * @param osh
//     * @param shippingDetails
//     * @param logSign
//     * @param url
//     * @return
//     */
//    public static CalOrderContent orderReceipt(Map<Long, BigDecimal> orderReceiptItem, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> shippingDetails, String logSign, String url) {
//        long orderCode = osh.getOrderId();
//        try {
//            JSONObject content = getReceiptServiceRespByItem(orderReceiptItem, osh, shippingDetails, url, logSign, osh.getVenderId());
//            if (content == null || StringUtils.isEmpty(content.toJSONString())) {
//                log.info(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务返回报文为空。");
//                throw new com.lsh.oms.core.exception.BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务返回报文为空。");
//            }
//            CalOrderContent calOrderContent = new CalOrderContent();
//            if (!content.getString("return").startsWith("[")) {
//                calOrderContent.setReturnContent(JSONObject.parseObject(content.getString("return"), CalOrderReturnContent.class));
//            }
//            if (!content.getString("receipt").startsWith("[")) {
//                calOrderContent.setReceipt(JSONObject.parseObject(content.getString("receipt"), CalOrderReceiptContent.class));
//            }
//            return calOrderContent;
//        } catch (Throwable e) {
//            log.error(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务失败。");
//            log.error(e.getMessage(), e);
//            throw new com.lsh.oms.core.exception.BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务失败。");
//        }
//    }

    /**
     * 商品码签收
     *
     * @param received
     * @param osh
     * @param osds
     * @param uri
     * @param logSign
     * @return
     * @throws BusinessException
     */
    public static JSONObject getReceiptServiceRespByItem(Map<Long, BigDecimal> received, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> osds, String uri, String logSign, Long venderId) throws BusinessException {

        log.info("List<OrderShippingDetail> osds" + JSON.toJSONString(osds));

        boolean sectionFlag = true;
        if (received == null || received.isEmpty()) {
            sectionFlag = false;
        }

        JSONArray itemList = new JSONArray(osds.size());
        if (sectionFlag) {
            for (Map.Entry<Long, BigDecimal> entry : received.entrySet()) {
                JSONObject item = new JSONObject(4);
                item.put("item_id", entry.getKey());
                item.put("real_qty", entry.getValue());
                itemList.add(item);
            }
        }

        log.info(logSign + " :itemList is " + itemList.toJSONString());

        JSONArray shippingInfoDetailList = new JSONArray(osds.size());
        for (OrderShippingDetail osd : osds) {
            JSONObject item = JSON.parseObject(osd.getExt());
            item.put("item_code", osd.getItemCode());
            item.put("sku_id", osd.getSkuId().toString());
            item.put("sku_name", osd.getSkuName());
            item.put("sale_unit", osd.getSaleUnit().toString());
            item.put("real_qty", osd.getRealQty());
            item.put("qty", osd.getQty());
            item.put("money", osd.getMoney().toString());
            item.put("price", osd.getPrice().toString());
            if (sectionFlag) {
                item.put("item_id", osd.getItemId());
            }

            shippingInfoDetailList.add(item);
        }

        JSONObject shipExt = JSON.parseObject(osh.getExt());
        log.info(logSign + ",shipExt ext " + shipExt.toJSONString());
        JSONObject extHeadInfo = shipExt.getJSONObject("head_info");
        log.info(logSign + ",shipExt ext head_info " + extHeadInfo.toJSONString());
        JSONObject shippingInfoParams = new JSONObject();

        shippingInfoParams.put("head_info", extHeadInfo);
        shippingInfoParams.put("detail_list", shippingInfoDetailList);

        List<BasicNameValuePair> pairs = new ArrayList<>(3);
        pairs.add(new BasicNameValuePair("order_id", osh.getOrderId().toString()));

        if (sectionFlag) {
            pairs.add(new BasicNameValuePair("item_list", itemList.toJSONString()));
        } else {
            pairs.add(new BasicNameValuePair("item_list", itemList.toJSONString()));
        }
        pairs.add(new BasicNameValuePair("shipping_info", shippingInfoParams.toJSONString()));
        HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
        log.info(logSign + ",签收请求计算服务参数shipping_info:" + shippingInfoParams.toJSONString());
        log.info(logSign + ",签收请求计算服务参数item_list or skulist:" + itemList.toJSONString());

        String result = HttpUtils.post(uri, entity, false, BaseGoodUtils.buildHeaders(venderId)).getData();
        log.info(logSign + ",黑狗签收请求计算服务返回:" + result);

        return JSON.parseObject(result).getJSONObject("content");
    }


}
